package com.qinsoft.frame.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qinsoft.frame.common.UserInfo;
import com.qinsoft.frame.messages.WriteMessage;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.internal.parser.json.JsonConverter;
import com.taobao.api.internal.util.json.ExceptionErrorListener;
import com.taobao.api.internal.util.json.JSONReader;
import com.taobao.api.internal.util.json.JSONValidatingReader;

public class JsonConvert {	
    /**
     * getResponse方法描述：首字母转大写
     * @param: 
     * @return:
     */
    public static String getResponse(String message)
    {
        String response = message.substring(2, message.indexOf(":")-1);
        String[] arr = response.split("_");
        String name = "";
        for (int i= 0; i<arr.length; i++) {
            arr[i]=Character.toUpperCase(arr[i].charAt(0))+arr[i].substring(1);
            name += arr[i];
        }
       return name;
    }
    /**
     * toObject方法描述：转换淘宝对象，不需要指定类型
     * @param: 
     * @return:
     */
    public static TaobaoResponse toObject(String message) throws Exception
    {
        JsonConverter con = new JsonConverter();
        Class<?> clazz = Class.forName("com.taobao.api.response."+getResponse(message));

        TaobaoResponse response = null;
        JSONReader reader = new JSONValidatingReader(new ExceptionErrorListener());
        Object rootObj = reader.read(message);
        if (rootObj instanceof Map<?, ?>) {
            Map<?, ?> rootJson = (Map<?, ?>) rootObj;
            Collection<?> values = rootJson.values();
            for (Object rspObj : values) {
                if (rspObj instanceof Map<?, ?>) {
                    Map<?, ?> rspJson = (Map<?, ?>) rspObj;
                    response = (TaobaoResponse) con.fromJson(rspJson, clazz);
                    response.setBody(message);
                    return response;
                }
            }
        }
        return null;
    }
    /**
     * toObjects方法描述：转换淘宝对象，不需要指定类型
     * @param: 
     * @return:
     */
    public static List<TaobaoResponse> toObjects(String message) throws Exception
    {
        Pattern regex = Pattern.compile("\\{.*?\\}\\}");
        Matcher mat = regex.matcher(message);
        List<TaobaoResponse> list = new ArrayList<TaobaoResponse>();
        while(mat.find())
        {
            list.add(toObject(mat.group(0)));
        }
        return list;
    }
	/**
	 * 转换淘宝对象，需要指定类型
	 * @param <T>: 淘宝类型
	 * @param message: json
	 * @param clazz: 对象类型
	 * @return T
	 */
	public static <T extends TaobaoObject> T toObject(String message, Class<T> clazz){
		JSONReader reader = new JSONValidatingReader(new ExceptionErrorListener());
		Object rootObj = reader.read(message);
		if (rootObj instanceof Map<?, ?>) {
			Map<?, ?> rootJson = (Map<?, ?>) rootObj;
			Collection<?> values = rootJson.values();
			for (Object obj : values) {
				if (obj instanceof Map<?, ?>) {
					Map<?, ?> rspJson = (Map<?, ?>) obj;
					try {
						return new JsonConverter().fromJson(rspJson, clazz);
					} catch (ApiException e) {
						WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.JsonConvert.toObject()", e);
					}
				}
			}
		}
		return null;
	}
	/**
     * 转换为UserInfo对象
     * @param message: json
     * @throws ApiException
     */
    public static UserInfo toUserInfo(String message){
        JSONReader reader = new JSONValidatingReader(new ExceptionErrorListener());
        Object rootObj = reader.read(message);
        if (rootObj instanceof Map<?, ?>) {
            Map<?, ?> rootJson = (Map<?, ?>) rootObj;
            try {
                return new JsonConverter().fromJson(rootJson, UserInfo.class);
            } catch (ApiException e) {
                WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.JsonConvert.toObject()", e);
            }
        }
        return null;
    }
	/**
	 * 转换淘宝对象，不需要指定类型
	 * @param message: json
	 * @return TaobaoObject
	 */
//	public static TaobaoObject toObject(String message){
//		JSONReader reader = new JSONValidatingReader(new ExceptionErrorListener());
//		Object rootObj = reader.read(message);
//		if (rootObj instanceof Map<?, ?>) {
//			Map<?, ?> rootJson = (Map<?, ?>) rootObj;
//			Collection<?> values = rootJson.values();
//			for (Object obj : values) {
//				if (obj instanceof Map<?, ?>) {
//					Map<?, ?> rspJson = (Map<?, ?>) obj;
//					try {
//						if(rootJson.containsKey("notify_item")){		//如果是item消息
//							return new JsonConverter().fromJson(rspJson,NotifyItem.class);
//						}
//						else if(rootJson.containsKey("notify_trade")){	//如果是trade消息
//							return new JsonConverter().fromJson(rspJson,NotifyTrade.class);
//						}
//						else if(rootJson.containsKey("notify_refund")){	//如果是refund消息
//							return new JsonConverter().fromJson(rspJson,NotifyRefund.class);
//						}
//					} catch (ApiException e) {
//						WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.JsonConvert.toObject()", e);
//					}
//				}
//			}
//		}
//		return null;
//	}
}
